package com.cn.boot.spring.service.impl;

import com.cn.boot.spring.common.CommonResult;
import com.cn.boot.spring.common.JwtTokenUtil;
import com.cn.boot.spring.entity.WxPermissionEntity;
import com.cn.boot.spring.entity.WxUserEntity;
import com.cn.boot.spring.mapper.WxUserMapper;
import com.cn.boot.spring.service.IWxUserService;
import com.cn.boot.spring.vo.LoginParams;
import com.cn.boot.spring.vo.RegisterParams;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author Administrator
 * Created by Lxj in 2021/02/01
 */
@Service
@Transactional
//开启redsi缓存（user为缓存数据库中的文件夹名）
@CacheConfig(cacheNames = "wxUser")
public class WxUserServiceImpl implements IWxUserService {
    @Autowired
    private WxUserMapper wxUserMapper;
    /**
     * 注入密码加密解密器
     */
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 注入token生成工具类
     */
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public WxUserEntity getUserByName(String name) {
        List<WxUserEntity> users = wxUserMapper.getUserByName(name);
        Assert.isTrue(users.size() == 1, "账号或密码错误");
        return users.get(0);

    }

    @Override
    public List<WxPermissionEntity> getPermissionsByUserId(Integer id) {
        return wxUserMapper.getPermissionByUserId(id);
    }

    /**
     * 登录逻辑
     *
     * @param loginParams
     * @return
     * @throws BadCredentialsException
     * @author LXJ
     * @date 2021/01/30
     */
    @Override
    public CommonResult login(LoginParams loginParams) throws BadCredentialsException {
        //接收前台传来的账号密码
        String username = loginParams.getUsername();
        String password = loginParams.getPassword();
        //判断账号、密码是否为空
        if ("".equals(username)) {
            throw new BadCredentialsException("账号不能为空");
        }
        if ("".equals(password)) {
            throw new BadCredentialsException("密码不能为空");
        }
        //验证完成后，查询账号得到一个实体userByName
        WxUserEntity userByName = getUserByName(username);
        //存在账号则对比密码(注入passwordEncoder密码验证器)
        boolean matches = passwordEncoder.matches(password, userByName.getPassword());
        if (!matches) {
            throw new BadCredentialsException("密码错误");
        }
        //账号密码验证成功，生成Token（注入JwtTokenUtil工具类）
        String token = jwtTokenUtil.generateToken(userByName);
        //返回token
        return CommonResult.success(token);
    }

    /**
     * 查找用户是否存在
     */
    public Boolean findUserNameIsExists(String username){
        List<WxUserEntity> users  =  wxUserMapper.getUserByName(username);
     //如果存在，则返回true，否则返回false
     if(users.size()> 0){
         return true;
     }
     return false;
    }

    /**
     * 注册
     */
    @Override
    public CommonResult register(RegisterParams registerParams) {
        //接收前台传来的数据，判断用户是否已经存在
      Boolean result = findUserNameIsExists(registerParams.getUsername());
      if(result){
         return CommonResult.failed("当前用户已被注册，请重新输入！");
      }
      //当账号不存在时，则进行下一步
        //将密码加密
      String password = passwordEncoder.encode(registerParams.getPassword());
      registerParams.setPassword(password);
      //上传头像,将文件名保存到数据库中

      while(registerParams.getFiles().length > 0 ){
          registerParams.setIcon(registerParams.getIcon());
      }

      CommonResult all =  wxUserMapper.register(registerParams);
        return CommonResult.success(all);
    }

    /**
     * 用户列表
     * @return
     */
    @Cacheable(keyGenerator = "keyGenerator")
    @Override
    public CommonResult findAll() {
        List<WxUserEntity> list = wxUserMapper.findAll();
        return CommonResult.success(list);
    }

    /**
     * 模糊查询
     * @param wxUserEntity
     * @return
     */
    @Cacheable(keyGenerator = "keyGenerator")
    @Override
    public CommonResult fuzzyFindAll(WxUserEntity wxUserEntity) {
        List<WxUserEntity> list = wxUserMapper.fuzzyFindAll(wxUserEntity);
        return CommonResult.success(list);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Cacheable(keyGenerator = "keyGenerator")
    @Override
    public CommonResult pageFindAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<WxUserEntity> all = wxUserMapper.pageFindAll();
        return CommonResult.success(all);
    }

    /**
     * 单条删除
     * @param id
     * @return
     */
    @CacheEvict(key = "'findAll[]'")
    @Override
    public CommonResult del(Integer id) {
        Integer result = wxUserMapper.del(id);
        return CommonResult.success(result);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @CacheEvict(key = "'findAll[]'")
    @Override
    public CommonResult dels(List<Integer> ids) {
        ids.stream().forEach(wxUserMapper::del);
        return CommonResult.success(ids.size());
    }

    /**
     * 更新数据
     * @param wxUserEntity
     * @return
     */
    @Override
    public CommonResult update(WxUserEntity wxUserEntity) {
        Integer result = wxUserMapper.update(wxUserEntity);
        return CommonResult.success(result);
    }

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    @Override
    public CommonResult findById(Integer id) {
        WxUserEntity wxUserEntity = wxUserMapper.findById(id);
        return CommonResult.success(wxUserEntity);
    }
}
